class Rect {
    constructor(options) {
        this.dom = window.TAI_CANVAS
        this.ctx = this.dom.getContext("2d");
        this.options = options
        this.currentOptions = options
        this.id = options.id
        this.isDragAble = options.isDragAble || false
        if (!options.id) {
            throw "不能没有id"
        }

        this.isBeginDrag = false
        this.mousedown_pos = {x: null, y: null}
        this.mousemove_pos = {x: null, y: null}
        this.mouseup_pos = {x: null, y: null}
    }

    isInPath(click_x, click_y) {
        var {
            x, y, width, height,
            fill, stroke, strokeWidth
        } = this.options
        var ctx = this.ctx
        ctx.beginPath();
        ctx.rect(x || 0, y || 0, width || 10, height || 10);
        return ctx.isPointInPath(click_x, click_y)
    }

    _mousedown(x, y) {
        this.isBeginDrag = true
        this.mousedown_pos = {x, y}
    }

    _mouseup(x, y) {
        this.isBeginDrag = false;
        this.mouseup_pos = {x, y}
    }

    _mouseout(x, y) {
        this.isBeginDrag = false;
        this.mouseup_pos = {x, y}
    }

    _mousemove(x, y) {
        this.mousemove_pos = {x, y}
        var diff = {x: x - this.mousedown_pos.x, Y: y - this.mousedown_pos.y}
        if (this.isDragAble && this.isBeginDrag) {
            var {
                width, height,
                fill, stroke, strokeWidth
            } = this.options
            var ctx = this.ctx
            this.clear()
            ctx.restore()
            console.log(diff.x)
            ctx.rect(diff.x, y || 0, width || 10, height || 10);
            if (stroke) {
                ctx.lineWidth = strokeWidth || 1;
                ctx.strokeStyle = stroke || '#222';
                ctx.stroke();
            }
            if (fill) {
                ctx.fillStyle = fill || '#fff';
                ctx.fill();
            }
            this.currentOptions = {...this.currentOptions, x, y}
            ctx.save()
        }
    }

    clear() {
        var ctx = this.ctx
        var options = this.currentOptions
        var {
            x, y, width, height,
            fill, stroke, strokeWidth
        } = options
        ctx.clearRect(x, y, width, height,)
    }

    drawing() {
        var {
            x, y, width, height,
            fill, stroke, strokeWidth
        } = this.options
        var ctx = this.ctx

        ctx.rect(x || 0, y || 0, width || 10, height || 10);
        if (stroke) {
            ctx.lineWidth = strokeWidth || 1;
            ctx.strokeStyle = stroke || '#222';
            ctx.stroke();
        }
        if (fill) {
            ctx.fillStyle = fill || '#fff';
            ctx.fill();
        }
    }
}

export default Rect